import 'package:concierge/app/models/user_bean.dart';
import 'package:concierge/app/pages/bind_phone/logic.dart';
import 'package:concierge/app/req/apis/CommonApi.dart';
import 'package:concierge/app/req/apis/UserApi.dart';
import 'package:concierge/app/routes/app_routes.dart';
import 'package:concierge/app/service/GlobalService.dart';
import 'package:concierge/app/utils/Cacheutil.dart';
import 'package:concierge/app/widgets/CommonDialog.dart';
import 'package:concierge/generated/locales.g.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import 'state.dart';

class EmailLoginLogic extends GetxController {
  final EmailLoginState state = EmailLoginState();

  final globalService = Get.find<GlobalService>();
  @override
  void onInit() {
    super.onInit();
    state.email.value = globalService.lastEmail;
  }

  Future<void> sendEmail() async {
    if (state.email.value.isEmpty) {
      SmartDialog.showToast(LocaleKeys.enter_email_account.tr);
      return;
    }

    if (!state.email.value.isEmail) {
      SmartDialog.showToast(LocaleKeys.enter_valid_email.tr);
      return;
    }

    bool hasCreate = await CommonApi.instance.sendEmail(
      email: state.email.value,
    );
    if (hasCreate) {
      SmartDialog.showToast(LocaleKeys.send_email_success.tr);
      globalService.startEmailCountDown(state.email.value);
    } else {
      SmartDialog.showToast(LocaleKeys.send_email_failed.tr);
    }
  }

  Future<void> login() async {
    if (state.email.value.isEmpty) {
      SmartDialog.showToast(LocaleKeys.enter_email_account.tr);
      return;
    }

    if (!state.email.value.isEmail) {
      SmartDialog.showToast(LocaleKeys.enter_correct_email.tr);
      return;
    }

    if (state.code.value.isEmpty) {
      SmartDialog.showToast(LocaleKeys.enter_email_verification_code.tr);
      return;
    }
    var res = await UserApi.instance.loginByEmail(
      email: state.email.value,
      code: state.code.value,
    );

    var body = res.body;
    if (body is Map) {
      if (body.containsKey("session_id") &&
          body['session_id'].toString().isNotEmpty) {
        await showCommonDialog(
          content: LocaleKeys.bind_phone_required.tr,
          dialogBtnParam: DialogButtonParam(
            onlyOneButton: false,
            showDivider: false,
            rightText: LocaleKeys.go_bind.tr,
            leftText: LocaleKeys.cancel.tr,
            onRightTap: () {
              Get.toNamed(
                Routes.bind_phone,
                arguments: BindPhoneParam(type: BindPhoneType.email, obj: body),
              );
            },
          ),
        );
      } else {
        await saveUser(UserBean.fromJson(body));
        globalService.cancelEmail();
        Get.offAllNamed(Routes.main);
      }
    }
  }
}
